<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="page.param.name" placeholder="关键字查询" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="info" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="deleteUser">
        删除
      </el-button>
      <el-button :loading="passwordLoading" class="filter-item" style="margin-left: 10px;" type="warning" icon="el-icon-edit" @click="restUserPassword">
        密码重置
      </el-button>
      <el-button class="filter-item" @click="uploadVisible = true;fileList = []">
        导入
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      height="500"
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="序号" type="index" width="50" />
      <el-table-column align="center" label="学号" prop="num" width="200" />
      <el-table-column align="center" label="姓名" prop="name" width="200" />
      <el-table-column align="center" label="性别" prop="sex" width="80" />
      <el-table-column align="center" label="所在院系" prop="faculty" width="200" />
      <el-table-column align="center" label="专业" prop="major" width="200" />
      <el-table-column align="center" label="班级" prop="grades" width="200" />
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="110" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="viewClick(scope.row)">查看</el-button>
          <el-button type="text" size="small" @click="editClick(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-show="page.total>0" :total="page.total" :current-page="page.page" :page-size="page.limit" @current-change="fetchData" />
    <el-dialog title="学生" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="registerRules">
        <el-form-item label="姓名" label-width="150px" prop="name">
          <el-input
            ref="name"
            v-model="form.name"
            :readonly="state==='view'"
            placeholder="请输入姓名"
            name="name"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item label="学号" label-width="150px" prop="num">
          <el-input
            ref="num"
            v-model="form.num"
            :readonly="state==='view'"
            placeholder="请输入学号"
            name="num"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item label="性别" label-width="150px" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别" :disabled="state==='view'">
            <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="院系" label-width="150px" prop="faculty">
          <el-input
            ref="faculty"
            v-model="form.faculty"
            :readonly="state==='view'"
            placeholder="请输入院系"
            name="faculty"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item label="专业" label-width="150px" prop="major">
          <el-input
            ref="major"
            v-model="form.major"
            :readonly="state==='view'"
            placeholder="请输入专业"
            name="major"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item label="班级" label-width="150px" prop="grades">
          <el-input
            ref="grades"
            v-model="form.grades"
            :readonly="state==='view'"
            placeholder="请输入班级"
            name="grades"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item v-if="state==='add'" label="密码" label-width="150px" prop="password">
          <el-input
            ref="password"
            v-model="form.password"
            placeholder="请输入密码"
            name="password"
            type="password"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item v-if="state==='add'" label="确认密码" label-width="150px" prop="r_password">
          <el-input
            ref="r_password"
            v-model="form.r_password"
            placeholder="请再次输入密码"
            name="r_password"
            type="password"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item label="状态" label-width="150px" prop="status">
          <el-select v-model="form.status" name="status" ref="status" placeholder="请选择报道状态" >
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.name" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div v-if="state!=='view'" slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="导入" :visible.sync="uploadVisible">
      <el-upload
        class="upload-demo"
        :headers="headers"
        :limit="1"
        :file-list="fileList"
        :action="baseUrl+'/file/import'"
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传.xls文件</div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { page, add, edit, deleteByIds, restPassword } from '@/api/student'
import { getToken } from '@/utils/auth'
import { validNotNull } from '@/utils/validate'
import { Message } from 'element-ui'
import { mapGetters } from 'vuex'

export default {
  data() {
    const validNot = (rule, value, callback) => {
      if (!validNotNull(value)) {
        callback(new Error('必填'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度的要大于6位'))
      } else {
        callback()
      }
    }
    const validateTwoPassword = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }
    return {
      list: null,
      listLoading: true,
      loading: false,
      passwordLoading: false,
      page: {
        page: 1,
        size: 10,
        total: 0,
        param: { name: '' }
      },
      multipleSelection: [],
      dialogFormVisible: false,
      state: 'add',
      form: {
        name: '',
        num: '',
        sex: '',
        faculty: '',
        grades: '',
        major: '',
        password: '',
        r_password: '',
        status: ''
      },
      registerRules: {
        name: [{ required: true, trigger: 'blur', validator: validNot }],
        num: [{ required: true, trigger: 'blur', validator: validNot }],
        sex: [{ required: true, trigger: 'blur', validator: validNot }],
        faculty: [{ required: true, trigger: 'blur', validator: validNot }],
        grades: [{ required: true, trigger: 'blur', validator: validNot }],
        major: [{ required: true, trigger: 'blur', validator: validNot }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        r_password: [{ required: true, trigger: 'blur', validator: validateTwoPassword }],
        status: [{ required: true, trigger: 'change', validator: validNot }]
      },
      options: [ '男', '女' ],
      statusOptions: [ { name: '未报道', value: 1 }, { name: '报道', value: 2 },{ name: '不报道', value: 3 } ],
      uploadVisible: false,
      baseUrl: 'http://localhost:8080',
      headers: { Authorization: getToken() },
      fileList: []
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取列表数据
    fetchData(val) {
      if (val != null && val !== '') {
        this.page.page = val
      }
      this.listLoading = true
      page(this.page).then(response => {
        this.list = response.result.records
        this.page.total = response.result.total
        this.listLoading = false
      })
    },
    // 选中改变
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 列表筛选
    handleFilter() {
      this.fetchData()
    },
    // 新增方法
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.state === 'add') {
            add(this.form).then(res => {
              if (res.code === '200'){
                this.dialogFormVisible = false
                this.fetchData()
                Message.success(res.result)
              }
            }).catch((err) => {
              console.log(err)
            })
          } else {
            edit(this.form).then(res => {
              if (res.code === '200'){
                this.dialogFormVisible = false
                this.fetchData()
                Message.success(res.result)
              }
            }).catch((err) => {
              console.log(err)
            })
          }
        } else {
          return false
        }
      })
    },
    // 新增
    handleCreate() {
      this.state = 'add'
      this.dialogFormVisible = true
      this.form = {
        name: '',
        num: '',
        sex: '',
        faculty: '',
        grades: '',
        major: '',
        password: '',
        r_password: '',
        status: ''
      }
    },
    // 查看
    viewClick(data) {
      this.state = 'view'
      this.dialogFormVisible = true
      this.form = data
    },
    // 修改
    editClick(data) {
      this.dialogFormVisible = true
      this.state = 'edit'
      this.form = data
      this.form.password = null
    },
    // 删除
    deleteUser() {
      this.loading = true
      const ids = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          ids.push(item.id)
        })
        deleteByIds(ids).then(res => {
          this.loading = false
          if (res.code === '200'){
            this.multipleSelection = []
            this.fetchData()
            Message.success(res.result)
          }
        }).catch((err) => {
          this.loading = false
          console.log(err)
        })
      } else {
        this.loading = false
        Message.error('请要修改的数据！')
      }
    },
    // 密码重置
    restUserPassword() {
      this.passwordLoading = true
      const ids = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          ids.push(item.id)
        })
        restPassword(ids).then(res => {
          this.passwordLoading = false
          if (res.code === '200'){
            this.multipleSelection = []
            this.fetchData()
            Message.success(res.result)
          }
        }).catch((err) => {
          this.passwordLoading = false
          console.log(err)
        })
      } else {
        this.passwordLoading = false
        Message.error('请要修改的数据！')
      }
    },
    beforeUpload(file) {
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (suffix === 'xls') {
        return true
      } else {
        this.$message.error('仅支持上传.xls文件！')
        return false
      }
    },
    uploadSuccess(response, file, fileList) {
      if (response.code === '200') {
        this.$message.success('上传成功！')
        this.uploadVisible = false
        this.fetchData()
      } else {
        this.$message.error('上传失败，请重新上传或联系管理员！')
      }
    },
  }
}
</script>
